<template>
  <div v-drag>
    <transition name="el-zoom-in-bottom">
      <div v-show="isVisible" class="inspectAttribute">
        <div class="u-main">
          <div class="attributeSearchForm">
            <el-table
              v-loading="loading"
              ref="utable"
              :data="propertiesData.filter(filters)"
              style="width: 100%"
              height="244"
              highlight-current-row
              border
              header-row-class-name="headRowClass"
              @row-click="tableRowClick($event)"
            >
              <el-table-column
                v-for="(field,index) in fields"
                :key="index"
                :prop="field.k"
                :label="field.k"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-input
                    v-if="rowIsEditIndex === scope.row._feature.id"
                    v-model="scope.row[field.k]"
                    clearable
                  />
                  <span v-if="rowIsEditIndex !== scope.row._feature.id">{{ scope.row[field.k] }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button icon="el-icon-position" circle @click="handleLocate(scope.row)" />
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteRow(scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <i class="tab-pane-header-btn el-icon-close" @click="closeAttributeTable" />
        </div>
        <div class="u-foot">
          <div class="device-filter-toolbar">
            <span class="device-filter-label">
              <b>筛选:</b>
            </span>
            <el-select v-model="queryField" class="query-select" size="mini" placeholder="请选择">
              <el-option
                v-for="(field,index) in fields"
                :key="index"
                :label="field.k"
                :value="field.k"
              />
            </el-select>
            <el-input v-model="query" class="filter" size="mini" placeholder="关键字搜索" clearable />
          </div>
          <div style="float:right">
            <el-pagination
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="10"
              :pager-count="5"
              :total="allCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import { mapState } from "vuex";
import Clone from "@/utils/clone";
import BoxUtil from "@/assets/js/utils/BoxUtil";

export default {
  name: "Index",
  directives: {
    drag: {
      // 指令的定义
      bind: function(el) {
        const odiv = el; // 获取当前元素
        odiv.onmousedown = e => {
          // 算出鼠标相对元素的位置
          const disX = e.clientX - odiv.offsetLeft;
          const disY = e.clientY - odiv.offsetTop;

          document.onmousemove = e => {
            // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            const left = e.clientX - disX;
            const top = e.clientY - disY;
            // 移动当前元素
            odiv.style.left = left + "px";
            odiv.style.top = top + "px";
          };
          document.onmouseup = e => {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    }
  },
  data() {
    return {
      currentPage: 1, // 初始页
      pageSize: 10, // 每页的数据
      loading: false, // 加载等待框
      query: "", // 查询条件
      queryField: "", // 查询字段
      total: 0, // 总记录数
      rowIsEditIndex: undefined,
      isPassed: false
    };
  },
  methods: {
    /**
     * 更改页数
     * @param size
     */
    handleSizeChange(size) {
      this.pageSize = size;
    },
    /**
     * 翻页
     * @param currentPage
     */
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },
    /**
     * 过滤条件
     * @param data
     * @param index
     * @param array
     * @returns {boolean}
     */
    filters(data, index, array) {
      if (data[this.queryField] && data[this.queryField] != "") {
        return data[this.queryField]
          .toLowerCase()
          .includes(this.query.toLowerCase());
      } else {
        return true;
      }
    },
    /**
     * 标记表格行属性
     * @param row
     */
    editRow(row) {
      this.rowIsEditIndex = this.rowIsEditIndex ? undefined : row._feature.id;
    },

    //
    tableRowClick() {
      this.$store.commit("xcgl/setProertiesShow", true);
      // this.rowIsEditIndex = this.rowIsEditIndex ? undefined : row._feature.id;
    },

    /**
     * 保存行属性
     * @param row
     */
    saveEdit(row) {
      this.rowIsEditIndex = undefined;
      row._feature.properties = Clone.cloneNot(row, "_feature");
    },
    /**
     * 定位
     */
    handleLocate(row) {
      this.mapService.setDrawControlHighLight("simple_select", {
        featureIds: [row._feature.id]
      });
      const coordinates = row._feature.geometry.coordinates;
      this.mapService.flyTo(row._feature.geometry, 15);
      this.bus.$emit("onLocate", row._feature);
    },
    /**
     * 删除数据
     * @param row
     */
    deleteRow(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.mapService._fireDrawControlDelete({ features: [row._feature] });
         
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    /**
     * 关闭属性表
     */
    closeAttributeTable() {
      this.$store.commit("xcgl/setEditTableVisible", false);
    },
    /**
     * @param 高亮编辑表行
     */
    setEditTableHighLightRow(ids) {
      if (ids.length === 0) {
        this.$refs.utable.setCurrentRow();
      } else {
        const index =
          this.allFeatureCollection.findIndex(o => o.id === ids[0]) + 1;
        this.currentPage = Math.ceil(index / this.pageSize);
        this.propertiesData.forEach(item => {
          if (item._feature.id === ids[0]) {
            this.$refs.utable.setCurrentRow(item);
            this.$refs.utable.bodyWrapper.scrollTop =
              (this.$refs.utable.bodyWrapper.scrollHeight / this.pageSize) *
              ((index - 1) % this.pageSize);
            return;
          }
        });
      }
    }
    /**
     * 文本校验
     * @param $event
     */
    // textValidate($event, field) {
    //   const index = this.fieldsType.findIndex(o => o.name === field);
    //   const f = this.fieldsType[index];
    //   this.isPassed = f.isRequired ? $event !== "" : true;
    //   switch (f.type) {
    //     case "DOUBLE": //double类型
    //     case "INT32":
    //       this.isPassed = Number.isInteger($event) || $event === "";
    //       break;
    //   }
    // }
  },
  computed: {
    ...mapState({
      /**
       * 属性字段
       * @param state
       */
      attributes(state) {
        return state.xcgl.selectTask ? state.xcgl.selectTask.attribute : {};
      },
      /**
       * 属性表可见
       * @param state
       * @returns {*}
       */
      isVisible(state) {
        return state.xcgl.editTableVisible;
      },
      /**
       * 属性表数据
       * @param state
       * @returns {any[]}
       */
      propertiesData(state) {
        const collection = state.xcgl.featureCollection;
        return collection.map(o => {
          const newClone = Clone.clone(o.properties);
          newClone["_feature"] = o;
          return newClone;
        });
      },
      /**
       * 总记录数
       * @param state
       * @returns {number}
       */
      allCount(state) {
        return state.xcgl.featureCollection.length
          ? state.xcgl.featureCollection.length
          : 0;
      },
      /**
       * 临时存当前选中的服务的要素几何
       */
      allFeatureCollection(state) {
        return state.xcgl.featureCollection;
      },
      /**
       *
       * 服务类型（点线面）
       * @param state
       */
      featureType(state) {
        return state.xcgl.selectFeature
          ? state.xcgl.selectFeature.type
          : undefined;
      },
      /**
       * 要素字段类型
       */
      fieldsType(state) {
        return state.xcgl.featureFields;
      },
      /**
       * 同步操作
       */
      mapService(state) {
        return state.xcgl.mapServiceRight;
      },
      mapServiceLeft(state) {
        return state.xcgl.mapServiceLeft;
      }
    }),
    /**
     * 属性字典
     * @returns {*}
     */
    fields() {
      if (this.attributes) {
        try {
          const a = this.attributes === "" ? {} : JSON.parse(this.attributes);
          const array = [];
          for (const k in a) {
            array.push({ k: k, v: a[k] });
          }
          return array;
        } catch (e) {
          console.warn("属性字段解析出错!");
        }
      }
      return [];
    }
  }
};
</script>

<style>
.inspectAttribute {
  position: absolute;
  bottom: 10px;
  right: 180px;
  z-index: 999;
  width: calc(100% - 550px);
  height: 280px;
  color: white;
  cursor: pointer;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 15px 15px rgba(0, 0, 0, 0.22);
}

.inspectAttribute .attributeCloseBtn {
  margin-top: 0px;
}

.inspectAttribute .u-main {
  height: 245px;
  background-color: rgba(255, 255, 255, 1);
}

.inspectAttribute .u-foot {
  height: 35px;
  background: #1885c6;
}

.inspectAttribute .el-table td,
.el-table th {
  padding: 5px 0;
}

.inspectAttribute .el-input__inner {
  height: 30px;
  border-radius: 0px;
}

.inspectAttribute .el-button {
  margin-top: 4px;
  padding: 2px 2px;
}

.inspectAttribute .filter {
  width: 150px;
}

.inspectAttribute .attributeSearcForm {
  float: right;
  margin-right: 10px;
}

.inspectAttribute .el-form-item {
  margin-bottom: 0px;
}

.inspectAttribute .headRowClass {
  color: #fff;
  line-height: 10px;
}

.inspectAttribute .headRowClass th {
  background-color: #1885c6;
}

.inspectAttribute .tab-pane-header-btn {
  position: absolute;
  right: -19px;
  margin: 10px;
  top: -20px;
  font-size: 16px;
  transition: transform 0.3s;
  background-color: #f44336;
  border-radius: 10px;
  color: #fff;
  padding: 2px;
  z-index: 900;
  cursor: pointer;
}

.inspectAttribute .tab-pane-header-btn {
  position: absolute;
  right: -19px;
  margin: 10px;
  top: -20px;
  font-size: 16px;
  transition: transform 0.3s;
  background-color: #f44336;
  border-radius: 10px;
  color: #fff;
  padding: 2px;
  z-index: 900;
}

.inspectAttribute .tab-pane-header-btn:hover {
  cursor: pointer;
}

.inspectAttribute .device-filter-toolbar {
  display: inline-block;
  margin-top: 2px;
  margin-left: 10px;
}

.inspectAttribute .device-filter-label {
  color: #fff;
  font-size: 14px;
}

.inspectAttribute .el-table__footer-wrapper,
.el-table__header-wrapper {
  overflow: hidden;
  background: #1885c6;
}
</style>
